package levelrewind.android.app.model;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;

import android.util.Log;

/*
 * 
 * */
public class RestClient {
	
	public RestClient(){}
	
	/*
	 * Method to GET
	 * */
	public String queryRESTurl(String url) {
        HttpGet httpget = new HttpGet(url);
        return executeRequest(httpget);
	}
	
	/*
	 * Method to POST
	 * */
	public String postRESTurl(String url, ArrayList<NameValuePair> params) {
		HttpPost request = new HttpPost(url); 
        request.addHeader("Content-Type", "application/x-www-form-urlencoded"); 
        try {
			request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} 
        return executeRequest(request); 

	}
	
	public String putRESTurl(String url, ArrayList<NameValuePair> params) {
		HttpPut request = new HttpPut(url); 
        request.addHeader("Content-Type", "application/x-www-form-urlencoded"); 
        try {
			request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} 
        return executeRequest(request); 

	}
	
	/*
	 * Method to execute request
	 * */
	private String executeRequest(HttpUriRequest request) 
	{ 
		String response = null;
	    HttpClient client = new DefaultHttpClient(); 
	    HttpResponse httpResponse; 
	    try 
	    { 
	        httpResponse = client.execute(request); 
	        Log.i(RestDataHandler.class.getSimpleName(), "Status:[" + httpResponse.getStatusLine().toString() + "]");
	        HttpEntity entity = httpResponse.getEntity(); 
	 
	        if (entity != null) 
	        { 
	            InputStream instream = entity.getContent(); 
	            response = Util.convertStreamToString(instream); 
	            instream.close(); 
	        } 
		 } catch (ClientProtocolException e) {
	         Log.e("REST", "There was a protocol based error", e);
		 } catch (IOException e) {
		         Log.e("REST", "There was an IO Stream related error", e);
		 }
	    
		return response; 
	} 
}
